#include "temperature_reader.h"

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "esp_log.h"

#define TEMP_CTRL_UART_NUM 1
#define TEMP_CTRL_UART_TX_PIN 42
#define TEMP_CTRL_UART_RX_PIN 1
#define TEMP_CTRL_BAUD 9600
#define TEMP_CTRL_UART_RTS_PIN 2
#define TEMP_CTRL_UART_CTS_PIN UART_PIN_NO_CHANGE

static const char *TAG = "TEMP CTRL UART CONTROL";
#define BUF_SIZE (1024)
#define RD_BUF_SIZE (BUF_SIZE)
void temp_ctrl_uart_init()
{
    /* Configure parameters of an UART driver,
     * communication pins and install the driver */
    uart_config_t uart_config = {
        .baud_rate = TEMP_CTRL_BAUD,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE};
    int intr_alloc_flags = 0;

    ESP_ERROR_CHECK(uart_driver_install(TEMP_CTRL_UART_NUM, BUF_SIZE * 2, 0, 0, NULL, intr_alloc_flags));
    ESP_ERROR_CHECK(uart_param_config(TEMP_CTRL_UART_NUM, &uart_config));
    ESP_ERROR_CHECK(uart_set_pin(TEMP_CTRL_UART_NUM, TEMP_CTRL_UART_TX_PIN, TEMP_CTRL_UART_RX_PIN, TEMP_CTRL_UART_RTS_PIN, TEMP_CTRL_UART_CTS_PIN));
    ESP_ERROR_CHECK(uart_set_mode(TEMP_CTRL_UART_NUM, UART_MODE_RS485_HALF_DUPLEX));
}
void temp_ctrl_uart_free()
{
    int ret = uart_is_driver_installed(TEMP_CTRL_UART_NUM);
    if (ret)
    {
        uart_driver_delete(TEMP_CTRL_UART_NUM);
    }
}
static char recieve[255] = {0};

void temp_ctrl_read(float *value)
{

    memset(recieve, 0, 255);

    static char cmd[8] = {0x02, 0x03, 0x23, 0x8d, 0x00, 0x02, 0x5f, 0x97};

    uart_write_bytes(TEMP_CTRL_UART_NUM, (const char *)cmd, 8);

    vTaskDelay(pdMS_TO_TICKS(100));

    int len = uart_read_bytes(TEMP_CTRL_UART_NUM, recieve, 255, 20 / portTICK_RATE_MS);
    
   // ESP_LOGI(TAG, "read data count:%d,data:%s",len,recieve);

    if (len >= 5)
    {
       /*for(int i = 0 ; i < len;i ++)
        {
              ESP_LOGI(TAG, "data index:%d,data:%X",i,recieve[i]);
        }
        */
        uint32_t tmp = recieve[3];
        uint32_t dot =  recieve[4];
        *value = (tmp << 8  | dot)/10.0f;
    }
    else
    {
        *value = -1;
    }
}
